package com.wzu.group2.action;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wzu.group2.dao.UserMapper;
import com.wzu.group2.pojo.Perms;
import com.wzu.group2.pojo.Role;
import com.wzu.group2.pojo.User;
import com.wzu.group2.service.IMailService;
import com.wzu.group2.service.UserToken;
import com.wzu.group2.service.SaltUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/user")
public class UserAction {
    @Resource
    UserMapper userMapper;
    @Resource
    private IMailService mailService;


// 传统登录
    @RequestMapping("/dologin")
    public String login(@RequestParam(value = "userName") String name,
                        @RequestParam(value = "password") String pwd, HttpSession session){
        System.out.println("---------- "+name+" ------ "+pwd);
        User u = userMapper.findUserByNameAndPWD(name,pwd);
        if (u != null){
            session.setAttribute("userinfo", u);
            return "index";
        }
        session.setAttribute("error","用户名或密码不正确");
        return "login";
    }


// 利用shiro完成登录
    @RequestMapping("/userlogin")
    public String userlogin(@RequestParam(value = "userName") String name,
                        @RequestParam(value = "password") String pwd,
                            HttpSession session) {
        try {
            Subject subject = SecurityUtils.getSubject();
            System.out.println(name+" "+pwd);
            UserToken token = new UserToken(name, pwd,"Custom");
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误!");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        session.setAttribute("error","用户名或密码不正确");
        return "redirect:/";
    }

//    普通退出
    @RequestMapping("/quit")
    public String quitUser(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("userinfo");
        System.out.println("-------用户退出---------");
        return "/login";
    }
// shiro退出
    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "/login";
    }

    @RequestMapping("/findAllByPage")
    public String findAllByPage(Model model,
                                     @RequestParam(value = "pn",defaultValue="1") Integer pageNow,
                                     @RequestParam(required=false,defaultValue="5") Integer pageSize){
        System.out.println("进来了！！！！");
        PageHelper.startPage(pageNow, pageSize);
        List<User> users = userMapper.getUserList();
        System.out.println(users.size());
        PageInfo<User> pageInfo = new PageInfo<User>(users,5);
        model.addAttribute("users", users);
        model.addAttribute("pageInfo", pageInfo);
        return "userlist";
    }

    /**
     * 修改用户信息
     * @param id
     * @param userCode
     * @param userName
     * @param userPassword
     * @param phone
     * @param userRole
     * @param address
     * @return 用户信息显示列表
     */
    @RequestMapping("/user_update")
    public String update(@RequestParam(value = "id") int id,
            @RequestParam(value = "userCode") String userCode,
                      @RequestParam(value = "userName") String userName,
                      @RequestParam(value = "userPassword") String userPassword,
                          @RequestParam(value = "phone") String phone,
                          @RequestParam(value = "userRole") int userRole,
                          @RequestParam(value = "address") String address){
        System.out.println("修改"+userCode+"---"+userName+"----"+userRole);
        User user = new User();
        User tempUser = userMapper.findUserById(id);
        user.setId(id);
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setAddress(address);
        user.setUserRole(userRole);
        user.setType(tempUser.getType());
        try {
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2021-9-8");
            user.setModifyDate(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        //设置初始密码
        String salt = SaltUtils.getSalt(8);
        //2.将随机盐保存到数据
        user.setSalt(salt);
        //3.明文密码进行md5 + salt + hash散列
        Md5Hash md5Hash = new Md5Hash(userPassword,salt,1024);
        user.setUserPassword(md5Hash.toHex());
        user.setSalt(salt);
        userMapper.updateUser(user);
        userMapper.update_user_role(id,userRole);
        return "redirect:/user/findAllByPage";

    }
    @RequestMapping("/changeType")
    public String changeType(@RequestParam(value = "id") int id,@RequestParam(value = "type") int type){
        System.out.println("正在修改用户状态...");
        User user = userMapper.findUserById(id);
        user.setType(type);
        userMapper.updateUser(user);
        System.out.println("用户状态改变："+user.getType());
        return "redirect:/user/findAllByPage";
    }

    /**
     * 添加用户
     * @param userCode
     * @param userName
     * @param phone
     * @param birthday
     * @param address
     * @param createBy
     * @param gender
     * @param userRole
     * @return
     */
    @RequestMapping("/add_user")
    public String addUser(@RequestParam(value = "userCode") String userCode,
                         @RequestParam(value = "userName") String userName,
                         @RequestParam(value = "phone") String phone,
                         @RequestParam(value = "birthday") String birthday,
                         @RequestParam(value = "address") String address,
                            @RequestParam(value ="createBy") int createBy,
                          @RequestParam(value = "gender")int gender,
                          @RequestParam(value = "userRole") int userRole,
                          Model model){
        System.out.println("正在添加："+userCode+"---"+userName);
        User tmp=userMapper.findUserByName(userCode);
        if(tmp==null){
            System.out.println("成功添加新用户："+userCode);
            User user = new User();
            user.setUserCode(userCode);
            user.setUserName(userName);
            user.setAddress(address);
            user.setPhone(phone);
            user.setType(1);
            //设置初始密码
            String salt = SaltUtils.getSalt(8);
            //2.将随机盐保存到数据
            user.setSalt(salt);
            //3.明文密码进行md5 + salt + hash散列
            Md5Hash md5Hash = new Md5Hash("123456",salt,1024);
            user.setUserPassword(md5Hash.toHex());
            user.setCreatedBy(createBy);
            user.setGender(gender);
            user.setUserRole(userRole);

            try {
                Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2021-9-8");
                user.setCreationDate(date);
                Date birth = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
                user.setCreationDate(birth);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            userMapper.addUser(user);
            userMapper.add_user_role(userMapper.findUserByName(userCode).getId(),userRole);
            return "redirect:/user/findAllByPage";

        }else{
            String message="用户编码已存在";
            List<Role> roles = userMapper.count_role();
            System.out.println("用户编码已存在，添加失败");
            model.addAttribute("roles",roles);
            model.addAttribute("message",message);
            return "useradd";
        }



    }

    /**
     * 修改用户密码（加密）
     * @param id
     * @param password
     * @param session
     * @return
     */
    @RequestMapping("/change_pwd")
    public String change_pwd(@RequestParam(value = "id") int id,
                             @RequestParam(value = "password") String password, HttpSession session){
        System.out.println("修改用户密码： "+id+" 新密码： "+password);
        //处理业务调用dao
        //1.生成随机盐
        String salt = SaltUtils.getSalt(8);
        //2.将随机盐保存到数据
        User user = userMapper.findUserById(id);
        user.setSalt(salt);
        //3.明文密码进行md5 + salt + hash散列
        Md5Hash md5Hash = new Md5Hash(password,salt,1024);
        user.setUserPassword(md5Hash.toHex());
        System.out.println("新密码： "+md5Hash.toHex());
        userMapper.updateUser(user);
        session.setAttribute("error","用户信息修改，请重新登录");
        return "index";

    }
    @RequestMapping("/del_user")
    public String del_user(@RequestParam(value = "id") int id){
        System.out.println("正在删除用户信息："+id);
        userMapper.deleteUser(id);
        return "redirect:/user/findAllByPage";
    }

    /**
     * 根据条件搜索用户
     * @param model
     * @param userCode
     * @return
     */
    @RequestMapping("/findByAdd")
    public String findByAdd(Model model, @RequestParam(value = "userCode") String userCode){
        List<User> userByAdd = userMapper.findUserByAdd(userCode);
        PageHelper.startPage(1, 5);
        PageInfo<User> pageInfo = new PageInfo<User>(userByAdd,5);
        List<Integer> roleList=userMapper.getUserRole();
        model.addAttribute("users", userByAdd);
        model.addAttribute("roleList",roleList);
        model.addAttribute("pageInfo", pageInfo);
        return "userlist";
    }

    /**
     * 发送邮件
     * @param theme
     * @param email
     * @param content
     * @return
     */
    @RequestMapping("/sendEmail")
    public String sendEmail( @RequestParam(value = "theme") String theme,
                             @RequestParam(value = "email") String email,
                             @RequestParam(value = "content") String content){
        mailService.sendSimpleMail(email,theme,content);
        return "index";
    }

    /**
     * 跳转修改用户界面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/toMod")
    public String toMod(@RequestParam(value = "id") int id, Model model){
        User user = userMapper.findUserById(id);
        System.out.println(user);
        List<Role> roles = userMapper.count_role();
        model.addAttribute("roles",roles);
        model.addAttribute("user",user);
        return "usermod";
    }

    /**
     * 查找所有禁用用户列表
     * @param model
     * @param pageNow
     * @param pageSize
     * @return
     */
    @RequestMapping("/find_all_ban")
    public String find_all_ban(Model model,
                               @RequestParam(value = "pn",defaultValue="1") Integer pageNow,
                               @RequestParam(required=false,defaultValue="5") Integer pageSize){
        PageHelper.startPage(pageNow, pageSize);
        List<User> users = userMapper.find_all_ban();
        PageInfo<User> pageInfo = new PageInfo<User>(users,5);
        List<Integer> roleList=userMapper.getUserRole();
        model.addAttribute("users", users);
        model.addAttribute("roleList",roleList);
        model.addAttribute("pageInfo", pageInfo);
        return "userBan";
    }

    /**
     * 查找所有权限
     * @param model
     * @param pageNow
     * @param pageSize
     * @return
     */
    @RequestMapping("/find_all_perm")
    public String find_all_perm(Model model,
                               @RequestParam(value = "pn",defaultValue="1") Integer pageNow,
                               @RequestParam(required=false,defaultValue="5") Integer pageSize){
        PageHelper.startPage(pageNow, pageSize);
        List<Perms> perms = userMapper.find_all_perm();
        PageInfo<Perms> pageInfo = new PageInfo<Perms>(perms,5);
        model.addAttribute("perms", perms);
        model.addAttribute("pageInfo", pageInfo);
        return "permList";
    }

    /**
     * 根据id修改对应的功能
     * 1、输入id，根据id查找
     * 2、将查找到的信息返回到修改界面permMod.html
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/find_permbyid")
    public String find_permbyid(Model model,
                                @RequestParam(value = "id") int id){
        Perms perms = userMapper.find_permbyid(id);
        model.addAttribute("perms",perms);
        return "permMod";
    }

    /**
     * 修改功能
     * @param model
     * @param name
     * @param url
     * @param id
     * @return
     */
    @RequestMapping("/permModify")
    public String permModify(Model model,
                             @RequestParam(value = "name") String name,
                             @RequestParam(value = "url") String url,
                             @RequestParam(value = "id") int id){
        System.out.println("----修改功能"+name+"-----"+url);
        Perms perms = new Perms();
        perms.setId(id);
        perms.setName(name);
        perms.setUrl(url);
        userMapper.permModify(perms);
        return "redirect:/user/find_all_perm";
    }

    /**
     * 添加功能
     * @param name
     * @param url
     * @return
     */
    @RequestMapping("/add_perm")
    public String add_perm(@RequestParam(value = "Pname") String name,
                           @RequestParam(value = "url") String url){
        Perms perms = new Perms();
        System.out.println("-------"+name+"--------"+url+"-----");
        perms.setName(name);
        perms.setUrl(url);
        userMapper.add_perm(perms);
        return "redirect:/user/find_all_perm";
    }

    /**
     * 删除对应的功能
     * @param id
     * @return
     */
    @RequestMapping("/del_perm")
    public String del_perm(@RequestParam(value = "id") int id){
        System.out.println("---正在删除功能"+id+"---");
        userMapper.del_perm(id);
        userMapper.del_perm_role(id);
        return "redirect:/user/find_all_perm";
   }

    /**
     * 修改角色信息
     * @param model
     * @return roleMod
     */
    @RequestMapping("/roleMod")
    public String roleMod(Model model,
                              @RequestParam(value = "id") int id){
        System.out.println(id);
        Role role = userMapper.findRolebyId(id);
//        PageHelper.startPage(pageNow, pageSize);
        List<Perms> perms = userMapper.find_all_perm();
        List<Integer> perms_id= userMapper.find_perms_id(id);
        System.out.println(perms_id);
//        PageInfo<Perms> pageInfo = new PageInfo<Perms>(perms,5);
        model.addAttribute("perms", perms);
        model.addAttribute("perms_id",perms_id);
//        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("role",role);
        return "Rolemod";
    }

    /**
     * 角色赋权
     * @param role_id
     * @param permList
     * @return
     */
    @RequestMapping("/add_role_perm")
    public String add_role_perm(@RequestParam(value = "role_id") int role_id,
                                @RequestParam(value = "permList") ArrayList<Integer> permList){
        System.out.println("-----配置角色 "+role_id);
        userMapper.delRole_Perm(role_id);
        if (permList.size()!=0){
            for(int i=0;i<permList.size();i++){
                userMapper.add_role_perm(role_id,permList.get(i));
                System.out.println("正在添加权限 "+permList.get(i)+" ---所属用户： "+role_id);
            }
        }

        return "redirect:/user/roleMod?id="+role_id;
    }

    /**
     * 查找所有的角色
     * @param model
     * @param pageNow
     * @param pageSize
     * @return
     */

    @RequestMapping("/find_all_role")
    public String find_all_role(@RequestParam(value = "pn",defaultValue="1") Integer pageNow,
                                @RequestParam(required=false,defaultValue="5") Integer pageSize,
                                Model model){
        PageHelper.startPage(pageNow, pageSize);
        List<Role> roles = userMapper.find_all_role();
        PageInfo<Role> pageInfo = new PageInfo<Role>(roles,5);
        model.addAttribute("roles", roles);
        model.addAttribute("pageInfo", pageInfo);
        return "rolelist";
    }

    /**
     * 添加角色
     * @param roleCode
     * @param roleName
     * @param createBy
     * @return
     */
    @RequestMapping("/add_role")
    public String add_role(Model model,
                            @RequestParam(value = "roleCode") String roleCode,
                           @RequestParam(value = "roleName") String roleName,
                           @RequestParam(value ="createBy") String createBy){
        //查重判断
        Role rolebyCode = userMapper.find_rolebyCode(roleCode);
        System.out.println(rolebyCode);
        if (rolebyCode == null){
            System.out.println("正在添加新角色！");
            Role role=new Role();
            role.setCreatedBy(createBy);
            role.setRoleName(roleName);
            role.setRoleCode(roleCode);
            try {
                Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2021-9-8");
                role.setCreationDate(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            userMapper.addRole(role);
            return "redirect:/user/find_all_role";
        }else{
            String message="角色编码已存在";
            System.out.println("角色编码已存在，添加失败");
            model.addAttribute("message",message);
            return "roleadd";
        }

    }
    @RequestMapping("/delRole")
    public String delRole(@RequestParam(value = "id") int id ){
        System.out.println("-----正在删除角色 "+id);
        userMapper.delRole(id);
        return "redirect:/user/find_all_role";
    }

}
